<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-row class="search-input">
          <el-form-item label="规则编码：">
            <el-input v-model="filters.ruleCode" clearable placeholder="规则编码"/>
          </el-form-item>
          <el-form-item label="规则名称：">
            <el-input v-model="filters.ruleName" clearable placeholder="规则名称"/>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="filters.status" clearable placeholder="状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="0"></el-option>
              <el-option label="停用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规则适用商家：">
            <el-select v-model="filters.merchantId" clearable placeholder="规则适用商家">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 按钮 -->
        <el-row class="search-button button20">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-refresh"
              :label="$t('action.reset')"
              type="primary"
              @click="resetForm('filters')"
            />
          </el-form-item>
          <el-form-item>
            <kt-button label="批量停用" type="active" @click="handleEnable"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :highlightCurrentRow="true"
      :content="pageResult"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showSelection="true"
      :showBatchDelete="false"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @selectionChange="selectionChange"
      ref="CyTable"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      ref="dataForm"
      width="50%"
      top="3vh"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="130px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="ID：" prop="id" v-if="false">
            <el-input
              v-model="dataForm.id"
              :disabled="true"
              auto-complete="off"
              placeholder="请输入ID"
            ></el-input>
          </el-form-item>
          <el-form-item label="优先级：" prop="priority">
            <el-input-number
              v-model="dataForm.priority"
              auto-complete="off"
              :min="1"
              style="width: 50%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="规则编码：" prop="code">
            <el-input
              v-model="dataForm.ruleCode"
              :disabled="true"
              auto-complete="off"
              placeholder="请输入规则编码"
            ></el-input>
          </el-form-item>
          <el-form-item label="规则名称：" prop="name">
            <el-input v-model="dataForm.ruleName" auto-complete="off" placeholder="请输入规则名称"></el-input>
          </el-form-item>
          <el-form-item label="规则适用商家：" prop="merchantId">
            <el-select
              v-model="dataForm.merchantId"
              style="width: 100%"
              placeholder="请选择"
              @change="selectionChange1"
            >
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规则状态：" prop="status">
            <el-radio v-model="dataForm.status" label="0">可用</el-radio>
            <el-radio v-model="dataForm.status" label="1">停用</el-radio>
          </el-form-item>
          <el-form-item label="有效期：" prop="time">
            <el-date-picker
              style="width: 50%"
              value-format="yyyy-MM-dd"
              @change="getTime"
              v-model="dataForm.time"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注：" prop="Remark">
            <el-input
              v-model="dataForm.remark"
              type="textarea"
              auto-complete="off"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
          <el-form-item label="寻源发仓策略：" prop="sourcingStrategy">
            <el-radio v-model="dataForm.strategy" label="1">降低收货频率-均衡分配发货仓</el-radio>
            <el-radio v-model="dataForm.strategy" label="2">降低高库存风险-均衡分配发货仓</el-radio>
          </el-form-item>
          <el-form-item label="匹配条件：" prop="matchCondition">
            <el-row>
              <el-button
                type="primary"
                size="mini"
                @click="addConditionDialog"
                round
                class="tr"
              >新增匹配条件</el-button>
            </el-row>
            <el-table
              :data="dataForm.matchCondition"
              :size="size"
              stripe
              style="width: 100%"
              border=""
            >
              <el-table-column prop="variableName" label="变量名"></el-table-column>
              <el-table-column prop="operator" label="运算符"></el-table-column>
              <el-table-column prop="conditionValue" label="条件值"></el-table-column>
              <el-table-column prop="operating" label="操作">
                <template slot-scope="scope">
                  <!-- <el-button type="primary" size="mini" @click="editConditionDialog">编辑</el-button> -->
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteConditionDialog(scope.$index, scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
    <!--匹配条件新增编辑界面-->
    <el-dialog
      :visible.sync="conditionDialog"
      width="50%"
      :title="operation1?'新增匹配条件':'修改匹配条件'"
      center
    >
      <el-form
        label-width="100px"
        ref="conditionDialogForm"
        :model="conditionDialogForm"
        :rules="conditionDialogFormRules"
        :size="size"
      >
        <el-row class="searchDialog-input">
          <el-form-item label="变量名：" prop="variableName">
            <el-select
              v-model="conditionDialogForm.variableName"
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option label="收货省份" value="收货省份"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运算符：" prop="operator">
            <el-select v-model="conditionDialogForm.operator" style="width: 100%" placeholder="请选择">
              <el-option label="=" value="="></el-option>
              <el-option label="!=" value="!="></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="条件值：" prop="conditionValue">
            <el-select
              v-model="conditionDialogForm.conditionValue"
              style="width: 100%"
              placeholder="请选择"
            >
              <el-option label="北京" value="北京"></el-option>
              <el-option label="天津" value="天津"></el-option>
              <el-option label="河北省" value="河北省"></el-option>
              <el-option label="山西省" value="山西省"></el-option>
              <el-option label="上海" value="上海"></el-option>
              <el-option label="安徽省" value="安徽省"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="conditionDialog = false">取 消</el-button>
        <el-button type="primary" @click.native="conditionSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import CyTable from "@/views/Core/ProductTable";
export default {
  components: {
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      options: {},
      size: "small",
      filters: {
        code: "",
        name: "",
        status: "",
        shopId: "",
        ruleCode: null,
        ruleName: null,
        isDelete: 0,
        merchantId: null
      },
      checked: [],
      columns: [
        {
          prop: "priority",
          label: "优先级",
          minWidth: 50
        },
        {
          prop: "ruleCode",
          label: "规则编码",
          minWidth: 120
        },
        {
          prop: "ruleName",
          label: "规则名称",
          minWidth: 120
        },
        {
          prop: "merchantName",
          label: "规则适用商家",
          minWidth: 120
        },
        {
          prop: "status",
          label: "状态",
          minWidth: 120,
          formatter: function(row, cloum, cellValue) {
            if (cellValue == 0) {
              return "可用";
            } else if (cellValue == 1) {
              return "停用";
            } else {
              return "-";
            }
          }
        }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      filterColumns: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10
      },
      pageResult: [],
      totalSize: 0,
      editLoading: false,
      conditionDialog: false,
      operation: false, // true:新增, false:编辑
      operation1: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      tableData: [],
      dataFormRules: {
        priority: [
          {
            required: true,
            message: "请输入优先级",
            trigger: "blur"
          },
          {
            required: true,
            message: "请输入优先级",
            trigger: "change"
          }
        ],
        status: [
          {
            required: true,
            message: "请输入规则状态",
            trigger: "change"
          }
        ],
        ruleName: [
          {
            required: true,
            message: "请输入规则名称",
            trigger: "blur"
          }
        ],
        time: [
          {
            required: true,
            message: "请输入有效期",
            trigger: "blur"
          }
        ],
        strategy: [
          {
            required: true,
            message: "请输入寻源发仓策略",
            trigger: "blur"
          }
        ],
        matchCondition: [
          {
            type: "array",
            required: true,
            message: "请输入匹配条件",
            trigger: "change"
          }
        ]
      },

      // 新增编辑界面数据
      dataForm: {
        id: 0,
        ruleName: "",
        ruleCode: "",
        priority: "",
        merchantName: "",
        matchCondition: [],
        strategy: "",
        remark: "",
        time: "",
        status: "",
        startDate: "",
        endDate: "",
        isDelete: 0
      },
      // 匹配条件表单
      conditionDialogForm: {
        routeSplitWarehouseId: "",
        variableName: "",
        operator: "",
        conditionValue: ""
      },
      conditionDialogFormRules: {
        variableName: [
          {
            required: true,
            message: "请输入变量名",
            trigger: "blur"
          }
        ],
        operator: [
          {
            required: true,
            message: "请输入运算符",
            trigger: "blur"
          }
        ],
        conditionValue: [
          {
            required: true,
            message: "请输入条件值",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.initColumns();
    this.findPage();
    this.queryShopName();
  },
  methods: {
    //多选框
    selectionChange: function(params) {
      this.checked = params.selections;
    },
    //商家名选择框
    selectionChange1: function(id) {
      this.options.find(item => {
        if (item.id === id) {
          //赋值商家名称
          this.dataForm.merchantName = item.name;
        }
      });
    },
    //商家初始化
    queryShopName() {
      var that = this;
      this.utils.request.queryMerchantListOther({}, function(data) {
        that.options = data.data;
      });
    },
    // 获取分页数据
    findPage: function(params) {
      let this_ = this;
      if (params == undefined || params == null) {
        params = {
          pageNum: this_.pageRequest.pageNum,
          pageSize: this_.pageRequest.pageSize
        };
      }
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = params.pageNum;
      this_.filters.limit = params.pageSize;
      this.utils.request.queryRoutRules(this_.filters, function(res) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        console.log(res.data.rows);
        this_.pageResult = res.data.rows;
        this_.totalSize = Number(res.data.total);
      });
    },
    // 批量删除
    handleDelete: function(data) {
      console.log(data);
      if (data.params[0].status == 0) {
        this.$message({
          message: "只能删除状态为【停用】的用户",
          type: "error"
        });
        return;
      }
      var that = this;
      that.utils.request.deleteConditions(
        {
          ids: data.params[0].id + "",
          isDelete: 0
        },
        res => {
          if (res.code == "0000") {
            that.findPage();
          } else {
            that.$message({
              message: "删除失败",
              type: "success"
            });
          }
        }
      );
    },
    // 匹配条件弹窗
    async deleteConditionDialog(rindex, row) {
      let that = this;
      await that.utils.request.deleteCondition(
        {
          id: row.id
        },
        function(data) {
          if (data.code == "0000") {
            //查询匹配条件
            let param = {
              isDelete: 0,
              routeSplitWarehouseId: row.routeSplitWarehouseId
            };
            that.utils.request.queryConditionListOther(param, function(data) {
              that.dataForm.matchCondition = data.data;
            });
          }
        }
      );
      if (row.routeSplitWarehouseId == undefined) {
        console.log(that.dataForm.matchCondition.length);
        for (let i = 0; i < that.dataForm.matchCondition.length; i++) {
          console.log(
            that.dataForm.matchCondition[i].variableName == row.variableName
          );
          console.log(that.dataForm.matchCondition[i].operator == row.operator);
          console.log(
            that.dataForm.matchCondition[i].conditionValue == row.conditionValue
          );
          if (
            that.dataForm.matchCondition[i].variableName == row.variableName &&
            that.dataForm.matchCondition[i].operator == row.operator &&
            that.dataForm.matchCondition[i].conditionValue == row.conditionValue
          ) {
            that.dataForm.matchCondition.splice(i, 1);
            i--;
          }
        }
        return;
      }
    },
    //新增匹配条件弹窗
    addConditionDialog() {
      this.conditionDialogForm = {};
      this.conditionDialog = true;
      this.operation1 = true;
    },
    editConditionDialog() {
      this.conditionDialog = true;
      this.operation1 = false;
      this.$nextTick(function() {
        this.conditionDialogForm = Object.assign({}, params.row);
      });
    },
    //添加匹配条件
    conditionSubmit() {
      if (!this.conditionDialogForm.variableName) {
        this.$message({
          message: "变量名不能为空",
          type: "error"
        });
        return;
      }
      if (!this.conditionDialogForm.operator) {
        this.$message({
          message: "运算符不能为空",
          type: "error"
        });
        return;
      }
      if (!this.conditionDialogForm.conditionValue) {
        this.$message({
          message: "条件值不能为空",
          type: "error"
        });
        return;
      }
      this.dataForm.matchCondition.push(this.conditionDialogForm);
      this.$refs["dataForm"].clearValidate("matchCondition");
      this.conditionDialog = false;
    },
    // 显示新增界面
    handleAdd: function() {
      //生成编码
      let this_ = this;
      this_.utils.request.orderRouteSplitWarehouseCreateCode(
        this_.filters,
        function(res) {
          this_.dataForm = {
            id: 0,
            priority:"",
            matchCondition: [],
            isDelete: 0,
            status: "0"
          };
          this_.dataForm.ruleCode = res.data;
        }
      );
      this.editDialogVisible = true;
      this.operation = true;
    },
    // 显示编辑界面
    handleEdit: function(params) {
      if (this.dataForm.priority != "") {
        this.$refs["dataForm"].clearValidate();
      }

      //查询匹配条件
      let this_ = this;
      let param = {};
      let matchConditionList = new Array();
      param.routeSplitWarehouseId = params.row.id;
      param.isDelete = 0;
      this.utils.request.queryConditionListOther(param, function(res) {
        if (res.data != null) {
          matchConditionList = res.data;
        }
        this_.dataForm = {
          id: params.row.id,
          ruleName: params.row.ruleName,
          ruleCode: params.row.ruleCode,
          priority: params.row.priority,
          merchantId: params.row.merchantId,
          matchCondition: matchConditionList,
          strategy: params.row.strategy,
          remark: params.row.remark,
          status: params.row.status,
          time: [params.row.startDate, params.row.endDate]
        };

        this_.editDialogVisible = true;
      });
    },
    // 提交编辑表单
    submitForm: function() {
      console.log(this.dataForm.startDate);
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            var this_ = this;
            this.utils.request.editderOrderRouteSplitWarehouse(
              this.dataForm,
              function(res) {
                if (res.code == "0000") {
                  this_.$message({
                    message: "操作成功",
                    type: "success"
                  });
                  this_.$refs["dataForm"].resetFields();
                  this_.editDialogVisible = false;
                  this_.findPage(null);
                } else {
                  this_.$message({
                    message: "操作失败, " + res.msg,
                    type: "error"
                  });
                }
              }
            );
          });
        }
      });
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    // 重置
    resetForm(formName) {
      this.filters = {
        code: "",
        name: "",
        status: "",
        shopId: "",
        isDelete: 0
      };
      this.findPage();
    },
    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    initColumns: function() {
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    getTime(t) {
      this.dataForm.startDate = this.dataForm.time[0];
      this.dataForm.endDate = this.dataForm.time[1];
    },
    //批量操作
    handleEnable: function() {
      let this_ = this;
      if (this_.checked.length >= 1) {
        let flag = true;
        let ids = "";
        $.each(this_.checked, function(index, val) {
          if (val.status == 1) {
            flag = false;
            this_.$message({
              message: "不可停用已停用的数据",
              type: "error"
            });
          } else {
            ids += val.id + ",";
          }
        });
        if (flag) {
          let params = {};
          params.ids = ids;
          this.utils.request.editRouteSplitWarehouseStatus(params, function(
            res
          ) {
            if (res.code == "0000") {
              this_.$message({
                message: "操作成功",
                type: "success"
              });
              this_.findPage(null);
            } else {
              this_.$message({
                message: "操作失败, " + res.msg,
                type: "error"
              });
            }
          });
        }
      } else {
        this_.$message({
          message: "必须选中一条数据",
          type: "error"
        });
      }
    }
  }
};
</script>

<style scoped lang='scss'>
.tr {
  text-align: right;
}
</style>
